import {
  // Icon ,
  Rect,
  subStyleProps,
} from '@antv/g6'
import { inferIconStyle } from '@antv/g6/esm/utils/node'
// import { connectImage } from '@antv/g6/esm/elements/shapes/image'
import type {
  BaseNodeStyleProps,
  IconStyleProps,
  LabelStyleProps,
} from '@antv/g6'
import {
  Group,
  Rect as GRect,
  type DisplayObjectConfig,
  type RectStyleProps as GRectStyleProps,
} from '@antv/g'
import { defaultStyles } from '../defaultStyle'

export interface CustomRectStyleProps extends BaseNodeStyleProps {
  width: number
  height: number
}
export type ParsedRectStyleProps = Required<CustomRectStyleProps>
export class CustomRect extends Rect {
  constructor(options: DisplayObjectConfig<CustomRectStyleProps>) {
    super(options)
  }
  /**
   * 绘制标签
   */
  protected getLabelStyle(
    attributes: Required<BaseNodeStyleProps>,
  ): false | LabelStyleProps {
    const style = super.getLabelStyle({
      ...attributes,
      labelPlacement: 'center',
    })
    return style ? (style as LabelStyleProps) : false
  }
  /**
   * 绘制主要图形
   */
  protected getKeyStyle(
    attributes: Required<BaseNodeStyleProps>,
  ): GRectStyleProps {
    return {
      ...super.getKeyStyle(attributes),
      width: defaultStyles.size[0],
      height: defaultStyles.size[1],
      fill: defaultStyles.bgColor,
      lineWidth: defaultStyles.borderWidth,
      stroke: defaultStyles.borderColor,
      strokeWidth: defaultStyles.borderWidth,
      radius: defaultStyles.radius,
    }
  }
  protected drawKeyShape(
    attrs: ParsedRectStyleProps,
    container: Group,
  ): GRect | undefined {
    const style = this.getKeyStyle(attrs)
    return this.upsert('key', GRect, style, container)
  }

  // 绘制图标-获取图标样式
  protected getIconStyle(
    attributes: Required<BaseNodeStyleProps>,
  ): false | IconStyleProps {
    if (
      attributes.icon === false ||
      (!attributes.iconText && !attributes.iconSrc)
    ) {
      return false
    }
    const originIconStyle = subStyleProps(
      this.getGraphicStyle(attributes),
      'icon',
    )
    const iconStyle: IconStyleProps = Object.assign(
      Object.assign(
        inferIconStyle(attributes.size!, originIconStyle),
        originIconStyle,
      ),
    )
    const { iconColor, iconFontFamily, iconSize, size } = defaultStyles
    Object.assign(iconStyle, {
      fill: iconColor,
      fontFamily: iconFontFamily,
      fontSize: iconSize,
      width: iconSize,
      height: iconSize,
      dx: 8,
      dy: size[1] ? (size[1] - iconSize) / 4 : 0, // 尽可能让图标垂直居中
    } as IconStyleProps)
    return iconStyle
  }
}
